package com.xkcyy.one.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xkcyy.one.dto.ConversationDTO;
import com.xkcyy.one.dto.MessageDTO;
import com.xkcyy.one.entity.Conversation;
import com.xkcyy.one.entity.Message;
import com.xkcyy.one.entity.User;
import com.xkcyy.one.exception.BusinessException;
import com.xkcyy.one.mapper.ConversationMapper;
import com.xkcyy.one.mapper.MessageMapper;
import com.xkcyy.one.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 对话服务实现类
 *
 * @author AI ASSISTANT
 */
@Service
public class ConversationService {
    
    private final ConversationMapper conversationMapper;
    private final MessageMapper messageMapper;
    private final UserMapper userMapper;
    
    @Autowired
    public ConversationService(ConversationMapper conversationMapper, MessageMapper messageMapper, UserMapper userMapper) {
        this.conversationMapper = conversationMapper;
        this.messageMapper = messageMapper;
        this.userMapper = userMapper;
    }
    
    
    public List<ConversationDTO> getAllConversations() {
        return conversationMapper.selectList(new Page<>(1,10),null).stream()
                .map(ConversationDTO::fromEntity)
                .collect(Collectors.toList());
    }
    
    
    public ConversationDTO getConversationById(Long id) {
        Conversation conversation = conversationMapper.selectById(id);
        if (conversation == null) {
            throw new BusinessException("对话不存在，ID: " + id);
        }
        return ConversationDTO.fromEntity(conversation);
    }
    
    
    public List<ConversationDTO> getConversationsByUserId(Long userId) {
        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在，ID: " + userId);
        }
        
        // 查询用户的对话列表
        LambdaQueryWrapper<Conversation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Conversation::getUserId, userId);
        return conversationMapper.selectList(queryWrapper).stream()
                .map(ConversationDTO::fromEntity)
                .collect(Collectors.toList());
    }
    
    
    @Transactional(rollbackFor = Exception.class)
    public ConversationDTO createConversation(Conversation conversation) {
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        conversation.setCreateTime(now);
        conversation.setUpdateTime(now);
        conversation.setId(IdUtil.getSnowflakeNextId());
        // 插入对话
        conversationMapper.insert(conversation);
        
        return ConversationDTO.fromEntity(conversation);
    }
    
    
    @Transactional(rollbackFor = Exception.class)
    public ConversationDTO updateConversation(Conversation conversation) {
        // 检查对话是否存在
        Conversation existingConversation = conversationMapper.selectById(conversation.getId());
        if (existingConversation == null) {
            throw new BusinessException("对话不存在，ID: " + conversation.getId());
        }
        
        // 设置更新时间
        conversation.setUpdateTime(LocalDateTime.now());
        
        // 更新对话
        conversationMapper.updateById(conversation);
        
        return ConversationDTO.fromEntity(conversation);
    }
    
    
    @Transactional(rollbackFor = Exception.class)
    public void deleteConversation(Long id) {
        // 检查对话是否存在
        Conversation existingConversation = conversationMapper.selectById(id);
        if (existingConversation == null) {
            throw new BusinessException("对话不存在，ID: " + id);
        }
        
        // 删除对话相关的消息
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getConversationId, id);
        messageMapper.delete(queryWrapper);
        
        // 删除对话
        conversationMapper.deleteById(id);
    }
    

}
